package com.ysh.utils;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/*
    定义工具类，实现读取核心配置文件，获取SqlSession对象
 */
public class MapperUtils {
    private static SqlSession sqlSession = null;
    // 获取mapper对象
    public static Object getMapper(Class<?> className){
        SqlSession sqlSession = null;
        try {
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession(true);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Object mapper = sqlSession.getMapper(className);
        return mapper;
    }

    // 释放资源
    public static void close(){
        if(sqlSession!=null) {
            sqlSession.close();
        }
    }
}
